import { create } from 'zustand';
import { createJSONStorage, persist } from 'zustand/middleware';
const _store = {
  token: '',
  userInfo: {
    username: '',
    nickname: '',
    avatar: '',
  },
};
const useStore = create(
  persist(
    (set, get) => ({
      count: 0,
      token: '',
      userInfo: {
        username: '',
        nickname: '',
        avatar: '',
      },
      //改变自身数据
      increment: () => set(state => ({ count: state.count + 1 })),
      //外部传递参数改变方法
      changnum: (param: number) =>
        set(state => ({ count: state.count + param })),
      changeNum: (param: number) => set({ count: param }),
      //get方法可以获取state
      //   changeuser: data => {
      //     const prevUserInfo = get()?.userInfo;
      //     set({ userInfo: { ...prevUserInfo, ...data } });
      //   },
      changeuser: data => {
        set(state => ({ userInfo: { ...state.userInfo, ...data } }));
      },
      setToken(token: string) {
        set({ token });
      },
      setUserInfo: data => {
        set(state => ({ userInfo: { ...state.userInfo, ...data } }));
      },
      reSetUserInfo() {
        set({ ..._store });
      },
    }),
    {
      name: 'user-storage', // 存储在localStorage中的key
      storage: createJSONStorage(() => localStorage), // 选择存储方式 这里要用createJSONStorage而不是window
    },
  ),
);
export default useStore;
